

import time
from DrissionPage import ChromiumPage, ChromiumOptions
import traceback
from DrissionPage.common import Keys
import requests
from fastapi import FastAPI
from openpyxl import load_workbook
import sys, json
import os
from pathlib import Path
from typing import List, Optional









"""
1.data数据是读取excel的内容

"""

def get_all_files(folder_path: str, recursive: bool = True, extensions: Optional[List[str]] = None) -> List[str]:
    """
    获取指定文件夹下的所有文件路径。

    :param folder_path: 目标文件夹路径
    :param recursive: 是否递归子文件夹，默认为 True
    :param extensions: 可选，只返回指定后缀的文件列表，如 ['.xlsx', '.txt']
    :return: 文件完整路径列表
    """
    folder = Path(folder_path)
    if recursive:
        files = [f for f in folder.rglob("*") if f.is_file()]
    else:
        files = [f for f in folder.iterdir() if f.is_file()]

    if extensions:
        extensions = [ext.lower() for ext in extensions]
        files = [f for f in files if f.suffix.lower() in extensions]

    return [str(f) for f in files]



try:
    co = ChromiumOptions()
    co.set_argument('--start-maximized')
    page = ChromiumPage(co)
    tab = page.latest_tab
    # 第一步
    tab.get('https://fxg.jinritemai.com/login/common')
    time.sleep(5)

    excel_path=data['excelData'][0]['该文件路径']

    # 打开 Excel
    wb = load_workbook(excel_path)
    sheet = wb.active  # 默认第一个工作表，如果有多个可用 wb['SheetName']

    # 假设 "状态" 是列名，需要找到列号
    status_col = None
    for col in range(1, sheet.max_column + 1):
        if sheet.cell(row=1, column=col).value == "状态":
            status_col = col
            break

    if not status_col:
        raise ValueError("未找到 '状态' 列")



    for index0, i in enumerate(data['excelData']):


        
        tab = page.latest_tab

        try:
            tab.ele('text=邮箱登录').click()
            time.sleep(2)
            tab.ele('xpath://*[@id="root"]/div/div[1]/div/div/div/div/div[2]/div[4]/div[1]/label/span/input').click()
            tab.ele('xpath://*[@id="ecomLoginForm"]/section/div[6]/button').click()
            tab.ele('xpath://*[@id="ecomLoginForm"]/section/div[3]/div[2]/div/div/div').click()
            time.sleep(20)
            tab.ele('xpath://*[@id="ecomLoginForm"]/section/div[5]/button').click()
            time.sleep(3)
            

        except:
            pass

        try:
            
            ele = tab.ele('text=商品创建')
            if ele:
                ele.click()
        except:
            pass

        
        time.sleep(3)
        tab = page.latest_tab
        

        folder = i["链接文件夹"]+"/主图"
        all_files = get_all_files(folder, recursive=True, extensions=[".jpg"])
        # 第八步//*[@id="saotu"]/div[1]/div/div[1]/div/div[2]/div[2]/div/div/div/div/ul/div[3]/label/input
        tab.ele('xpath://*[@id="saotu"]/div[1]/div/div[1]/div/div[2]/div[2]/div/div/div/div/ul/div[3]/label/input').input(all_files)

        
        # 模拟填写标题
        tab.ele('xpath://*[@id="pg-title-input"]').input(i["商品标题"])

        
        tab.ele('xpath://*[@id="saotu"]/div[2]/div[1]/div[1]/div/div').click()

        
        tab.ele('xpath://*[@id="saotu"]/div[2]/div[1]/div[4]/div/div[1]/label/input').input(i["类目"])
        time.sleep(2)
        tab.ele('xpath://*[@id="saotu"]/div[2]/div[1]/div[4]/div/div[1]/div/div/div[1]/div[1]/div[1]').click()
        time.sleep(2)
        tab.ele('xpath://*[@id="saotu"]/div[2]/div[2]/button/span').click()
        time.sleep(3)
        tab = page.latest_tab

        
        tab.ele('xpath://*[@id="goodsEditScrollContainer-基础信息"]/div[2]/div[4]/div/div[2]/div[2]/div/div/div/div[2]/span/span/input').input(i["导购短标题"])

        
        houdu=tab.ele('xpath://*[@id="rc_select_0"]')
        if houdu and i.get('厚度', '')!="":
            houdu.input(f"{i.get('厚度', '')}\n")

        houdu=tab.ele('xpath://*[@id="rc_select_1"]')
        if houdu and i.get('品牌', '')!="":
            houdu.input(f"{i.get('品牌', '')}\n")

        houdu=tab.ele('xpath://div[@attr-field-id="货号"]/div[2]/div/span/input')
        if houdu and i.get('货号', '')!="":
            houdu.input(f"{i.get('货号', '')}\n")

        houdu=tab.ele('xpath://*[@id="rc_select_2"]')
        if houdu and i.get('领型', '')!="":
            houdu.input(f"{i.get('领型', '')}\n")

        houdu=tab.ele('xpath://*[@id="rc_select_3"]')
        if houdu and i.get('适用性别', '')!="":
            houdu.input(f"{i.get('适用性别', '')}\n")

        houdu=tab.ele('xpath://*[@id="rc_select_4"]')
        if houdu and i.get('服装版型', '')!="":
            houdu.input(f"{i.get('服装版型', '')}\n")

        houdu=tab.ele('xpath://*[@id="rc_select_5"]')
        if houdu and i.get('组合件数', '')!="":
            houdu.input(f"{i.get('组合件数', '')}\n")

        houdu=tab.ele('xpath://*[@id="rc_select_6"]')
        if houdu and i.get('衣门襟', '')!="":
            houdu.input(f"{i.get('衣门襟', '')}\n")
        

        
        houdu=tab.ele('xpath://*[@id="rc_select_7"]')
        if houdu and i.get('适用年龄', '')!="":
            houdu.input(f"{i.get('适用年龄', '')}\n")

        houdu=tab.ele('xpath://*[@id="rc_select_8"]')
        if houdu and i.get('衣长', '')!="":
            houdu.input(f"{i.get('衣长', '')}\n")

        houdu=tab.ele('xpath://*[@id="rc_select_9"]')
        if houdu and i.get('款式', '')!="":
            houdu.input(f"{i.get('款式', '')}\n")

        houdu=tab.ele('xpath://*[@id="rc_select_10"]')
        if houdu and i.get('袖型', '')!="":
            houdu.input(f"{i.get('袖型', '')}\n")

        houdu=tab.ele('xpath://*[@id="rc_select_11"]')
        if houdu and i.get('袖长', '')!="":
            houdu.input(f"{i.get('袖长', '')}\n")

        
        houdu=tab.ele('xpath://div[@attr-field-id="风格"]/div[2]/div/div/div/div/div/div/input')
        if houdu and i.get('风格', '')!="":
            for fengge in i["风格"].split('|'):
                houdu.input(fengge)
                tab.actions.key_down(Keys.DOWN)  # 从Keys获取按键
                time.sleep(0.3)
                tab.actions.key_down(Keys.ENTER)          # 页面按下回车键

        houdu=tab.ele('xpath://div[@attr-field-id="服饰工艺"]/div[2]/div/div/div/div/div/div/input')
        if houdu and i.get('服饰工艺', '')!="":
            houdu.input(f"{i.get('服饰工艺', '')}\n")
            tab.actions.key_down(Keys.DOWN)  # 从Keys获取按键
            time.sleep(0.3)
            tab.actions.key_down(Keys.ENTER)          # 页面按下回车键

        houdu=tab.ele('xpath://div[@attr-field-id="图案"]/div[2]/div/div/div/div/div/div/input')
        if houdu and i.get('图案', '')!="":
            houdu.input(f"{i.get('图案', '')}\n")
            tab.actions.key_down(Keys.DOWN)  # 从Keys获取按键
            time.sleep(0.3)
            tab.actions.key_down(Keys.ENTER)          # 页面按下回车键

        houdu=tab.ele('xpath://div[@attr-field-id="适用季节"]/div[2]/div/div/div/div/div/div/input')
        if houdu and i.get('适用季节', '')!="":
            houdu.input(f"{i.get('适用季节', '')}\n")
            tab.actions.key_down(Keys.DOWN)  # 从Keys获取按键
            time.sleep(0.3)
            tab.actions.key_down(Keys.ENTER)          # 页面按下回车键

        houdu=tab.ele('xpath://div[@attr-field-id="功能"]/div[2]/div/div/div/div/div/div/input')
        if houdu and i.get('功能', '')!="":
            houdu.input(f"{i.get('功能', '')}\n")
            tab.actions.key_down(Keys.DOWN)  # 从Keys获取按键
            time.sleep(0.3)
            tab.actions.key_down(Keys.ENTER)          # 页面按下回车键

        houdu=tab.ele('xpath://div[@attr-field-id="面料材质"]/div[2]/div[2]/div/div[1]/div[1]/div/div/div/div/div/ul/div[1]/label/input')
        if houdu and i.get('链接文件夹', '')!="":
            houdu.input(f"{i.get('链接文件夹', '')}/吊牌.jpg")

        houdu=tab.ele('xpath://*[@id="rc_select_18"]')
        if houdu and i.get('材质', '')!="":
            houdu.input(f"{i.get('材质', '')}\n")
            tab.actions.key_down(Keys.DOWN)
            time.sleep(1)
            tab.actions.key_down(Keys.ENTER)  # 从Keys获取按键


        houdu=tab.ele('xpath://*[@id="rc_select_12"]')
        if houdu and i.get('里料材质成分含量', '')!="":
            houdu.input(f"{i.get('里料材质成分含量', '')}\n")

        houdu=tab.ele('xpath://div[@attr-field-id="上市时间"]/div[2]/div[2]/span/input')
        if houdu and i.get('上市时间', '')!="":
            houdu.input(f"{i.get('上市时间', '')}\n")

        
        houdu=tab.ele('xpath://div[@attr-field-id="克重"]/div[2]/div[2]/div/div/div/div/div/div/div/div/span/span/span/input')
        if houdu and i.get('克重', '')!="":
            houdu.input(f"{i.get('克重', '')}\n")

        houdu=tab.ele('xpath://div[@attr-field-id="里料材质"]/div[2]/div[2]/span/input')
        if houdu and i.get('里料材质', '')!="":
            houdu.input(f"{i.get('里料材质', '')}\n")

        houdu=tab.ele('xpath://*[@id="goodsEditScrollContainer-图文信息"]/div[2]/div[3]/div[2]/div[2]/div[2]/div[2]/div/div/span')
        if houdu:
            houdu.click()

        houdu=tab.ele('xpath://*[@id="goodsEditScrollContainer-图文信息"]/div[2]/div[4]/div/div[2]/div[2]/div/div/div/div/ul/div[1]/label/input')
        if houdu and i.get('链接文件夹', '')!="":
            houdu.input(f"{i.get('链接文件夹', '')}/白底.jpg")

        
        


        time.sleep(5)
        shangchaun=tab.ele('xpath://*[@id="__ffa-goods-popup-container__"]/div/div/div[2]/div/div/div[3]/div/div[2]/button')
        for t in range(4):
            if shangchaun:
                try:
                    shangchaun.click()
                    time.sleep(1)
                except:
                    pass
            time.sleep(1)

        houdu=tab.ele('xpath://*[@id="goodsEditScrollContainer-图文信息"]/div[2]/div[6]/div/div[2]/div[2]/div/div/div[3]/div[2]/div[1]/div[1]/div[2]/div/div/div/div/ul/label/input')
        if houdu and i.get('链接文件夹', '')!="":
            folder = i["链接文件夹"]+"/详情图"
            all_files = get_all_files(folder, recursive=True, extensions=[".jpg"])
            houdu.input(all_files)
        shangchaun=tab.ele('xpath://*[@id="__ffa-goods-popup-container__"]/div/div/div[2]/div/div/div[3]/div/div[2]/button')
        if shangchaun:
            shangchaun.click()

        time.sleep(1)
        houdu=tab.ele('xpath://*[@id="goodsEditScrollContainer-基础信息"]/div[2]/div[5]/div/div[2]/div[2]/div[2]/div/div/div[1]/div[3]/div/div/div/div[2]/div[2]/div/div[2]/div/div/div/div/div[2]/div/div/div/div/span/span/span/input')
        if houdu and i.get('占比', '')!="":
            houdu.input(f"{i.get('占比', '')}\n")

        if i.get('尺码信息', '')!="":
            tab.ele('xpath://*[@id="goodsEditScrollContainer-尺码信息"]/div[2]/div/div/div[2]/div/div/div[2]/div/button').click()
            time.sleep(2)
            tab.ele('xpath://*[@id="rc_select_19"]').input(i.get('尺码信息', ''))
            time.sleep(1)
            tab.actions.key_down(Keys.ENTER)  # 从Keys获取按键

        
        if i.get("发货模式",""):
            tab.ele(f'text={i["发货模式"]}').click()
        if i.get("现货发货时间",""):
            tab.ele(f'text={i["现货发货时间"]}').click()
        if i.get("订单库存计数",""):
            tab.ele(f'text={i["订单库存计数"]}').click()

        for index, yanse in enumerate(i["颜色"].split('|'), start=1):
            xpath_input = f'//*[@id="skuValue-颜色分类"]/div[{index}]/div/div[1]/div/div/span/input'
            input_ele = tab.ele(f'xpath:{xpath_input}')
            input_ele.input(yanse)
            
            # 等待下拉列表出现
            tab.ele('xpath://div[@id="goodsEditScrollContainer"]//ul/li[1]').click()
            # 点击确定按钮
            tab.ele('xpath://*[@id="goodsEditScrollContainer"]//button/span[contains(text(), "确定")]').click()
            time.sleep(1)


        for index, chicun in enumerate(i["尺码"].split('|'), start=1):
            # 动态 XPath
            xpath_input = f'//*[@id="skuValue-尺码大小"]/div[{index}]/div/div/div/div/span/input'
            input_ele = tab.ele(f'xpath:{xpath_input}')
            input_ele.input(chicun)

            # 等待下拉列表出现
            dropdown_li = tab.ele('xpath://div[@id="goodsEditScrollContainer"]//ul/li[1]')
            dropdown_li.click()

            # 点击确定按钮
            confirm_btn = tab.ele('xpath://*[@id="goodsEditScrollContainer"]//button/span[contains(text(), "确定")]')
            confirm_btn.click()
            time.sleep(1)





        
        houdu=tab.ele('xpath://*[@id="full-screen-card"]/div[2]/div[2]/div[2]/div/div[2]/div[3]/span/input')
        if houdu and i.get('价格', '')!="":
            houdu.input(f"{i.get('价格', '')}\n")

        houdu=tab.ele('xpath://*[@id="full-screen-card"]/div[2]/div[2]/div[2]/div/div[2]/div[4]/div/div/div/div[2]/div/div/div[2]/input')
        if houdu and i.get('库存', '')!="":
            houdu.input(f"{i.get('库存', '')}\n")

        houdu=tab.ele('xpath://*[@id="full-screen-card"]/div[2]/div[2]/div[2]/div/div[2]/div[5]/span/input')
        if houdu and i.get('商家编码', '')!="":
            houdu.input(f"{i.get('商家编码', '')}\n")

        houdu=tab.ele('xpath://*[@id="goodsEditScrollContainer-价格库存"]/div[2]/div[5]/div[2]/div[2]/div/div[2]/div[2]/input')
        if houdu and i.get('参考价', '')!="":
            houdu.input(f"{i.get('参考价', '')}\n")

        houdu=tab.ele('xpath://*[@id="full-screen-card"]/div[2]/div[2]/div[2]/div/div[2]/button[1]')
        if houdu:
            houdu.click()

        houdu=tab.ele('xpath://*[@id="goodsEditScrollContainer-价格库存"]/div[2]/div[6]/div[2]/div[2]/div/div')
        if houdu:
            houdu.click()

        houdu=tab.ele(f"text={i['参考价凭证类型']}")
        if houdu:
            houdu.click()

        houdu=tab.ele('xpath://*[@id="goodsEditScrollContainer-价格库存"]/div[2]/div[7]/div[2]/div[2]/div[1]/div/div/div/ul/div[1]/label/label/input')
        if houdu and i.get('链接文件夹', '')!="":
            path = i["链接文件夹"]+"/凭证图.jpg"
            houdu.input(path)

        tab.ele('xpath://*[@id="goodsEditScrollContainer-服务与履约"]/div[2]/div[1]/div[2]/div[2]/div/div/span[2]').click()
        time.sleep(2)
        tab.ele('text=发布商品').click()
        time.sleep(3)
        tab=page.latest_tab
        for e in range(4):
            houdu=tab.ele('xpath://*[@id="createSuccessGuideContainer"]/div[3]/div[1]/button')
            if houdu:
                try:
                    houdu.click()    
                    time.sleep(1)
                except:
                    pass
            time.sleep(1)
            
        sheet.cell(row=index0+2, column=status_col, value="已完成")
        wb.save(excel_path)  # 每行写入后保存，不关闭文件

    # 循环结束后再关闭工作簿
    wb.close()
except Exception as e:
    error_info = traceback.format_exc()
    print("====",e)














